import tool from "../../modules/tool"
import ws from '../../modules/ws'

// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    home: {},
    title: '后勤管理服务中心',
    mainCurrentPageIndex: 0,
    showOpenSubNotif: false,
    showCloseSN: false,
    subNotifFailCount: 0,
    showFeedBack: false,
    feedBackData: undefined,
    showLogo: false,
    loginingWelcomText: ''
  },

  // feedback - start
  handlePreviewBanner(e) {
    e = e.currentTarget.dataset
    wx.previewImage({
      urls: (() => {
        let t = tool.dcJSON(this.data.feedBackData.banner)
        for (let i = 0; i < t.length; i++) {
          t[i].src = tool.config.imagePrefix + t[i].src
        }
        return t
      })(),
      current: tool.config.imagePrefix + this.data.feedBackData.banner[e.index].src
    })
  },
  handleShowChatRoomList() {
    tool.chatRoom.showChatRoomListPage()
  },
  handleShowFeedBackSettings() {
    tool.feedback.settings()
  },
  hideFeedBack() {
    if (tool.isLogined()) {
      this.setData({
        showFeedBack: false
      })
      return
    }
    tool.handleNotLogin()
  },
  showPublishFeedBackPage() {
    wx.navigateTo({
      url: '/pages/fb_add/fb_add',
    })
  },
  async showNoticePage() {
    await tool.flow(async () => {
      let re = await tool.requestData('/feedback/notice/list', {}, 'get')
      if (re.status) {

      } else {
        throw re.content
      }
      tool.store.setItem('feedBack_notice', re.data)
      wx.navigateTo({
        url: '/pages/fb_notice/fb_notice',
      })
    }, err => wx.showToast({
      title: `${err}`,
      icon: 'error',
      duration: 800
    }))
  },
  async showMyFeedBackPage() {
    await tool.flow(async () => {
      let re = await tool.feedback.getMy()
      tool.store.setItem('feedBack_my', {
        data: re,
        openId: tool.store.getItem('openId')
      })
      wx.navigateTo({
        url: '/pages/fb_my/fb_my',
      })
    }, err => wx.showToast({
      title: `${err}`,
      icon: 'error',
      duration: 800
    }))
  },
  // feedback - end

  async handleCloseSubNotif() {
    tool.handleShowModel(`请尝试以下操作：点击小程序右上角的三个点图标，选择“设置”，进入“订阅消息”选项，将“接收通知”打开，并将“作业布置提醒”设置为“接收并提醒”。`, false)
    this.setData({
      showOpenSubNotif: false
    })
    wx.setStorageSync('subNotif', true)
  },

  getMessageTitle() {
    return `通知${(!tool.store.getItem('unreadNum')) ? '' : `（${tool.store.getItem('unreadNum')}）`}`
  },

  async handleSubNotif() {
    let re = await tool.handleSubWXNotif()
    if (re.status) {
      this.setData({
        showOpenSubNotif: false
      })
      wx.setStorageSync('subNotif', true)
      tool.handleShowToast('订阅成功', 'none')
    } else {
      this.setData({
        subNotifFailCount: this.data.subNotifFailCount + 1
      })
      if (this.data.subNotifFailCount >= 3) {
        this.setData({
          showCloseSN: true
        })
      }
      tool.handleShowToast('未完成订阅', 'error')
    }
  },

  handleShowAddPatrolPage() {
    if (!tool.isLogined()) {
      tool.handleNotLogin()
      return
    }
    if (this.data.mainCurrentPageIndex === 6) {
      tool.postFrontStatus(`首页 - 反馈（后勤e码通） 搜索反馈`)
      tool.page.getSearchFeedBackForm(e => {
        tool.page.searchFeedBack(e, '反馈搜索结果')
      })
      return
    }
    tool.postFrontStatus(`首页 - 巡查 搜索巡查`)
    tool.page.searchPatrol()
  },

  async handleGetHomeData() {
    this.setData({
      home: await tool.refreshHomeData()
    })
  },

  handleRefreshHomeData() {
    if ((this.data.refreshHomeDataTime && (new Date() - this.data.refreshHomeDataTime) > 1000 * 10) || this.data.refreshHomeDataTime === undefined) {
      this.setData({
        refreshHomeDataTime: new Date()
      })
      this.handleGetHomeData()
    } else {
      wx.showToast({
        title: `${parseInt(11 - (new Date() - this.data.refreshHomeDataTime) / 1000)}秒后才能刷新`,
        icon: 'none',
        duration: 800
      })
    }
  },

  async handleReadAll() {
    tool.handleShowModel('是否将全部通知设为已读状态？', true, () => tool.flow(async () => {
      tool.postFrontStatus(`首页 - 通知 全部通知设为已读`)
      let re = await tool.requestData('/notification/setAllRead')
      if (re.status) {
        tool.store.setItem('updateNotifications')
      } else {
        throw re.content
      }
    }, err => tool.handleShowToast(`${err}`)))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log(options)
    // return
    tool.store.onChange('showFeedBack', () => this.setData({
      showFeedBack: true
    }))
    tool.store.onChange('feedBackData', e => {
      this.setData({
        feedBackData: e
      })
    })
    tool.store.setItem('requestShowLoading', false)
    tool.updateWindowInfo()
    tool.setPageData(this)

    if (wx.getStorageSync('showLogo') === true) {
      this.setData({
        showLogo: true
      })
    }

    await tool.flow(async () => {
      // 登录
      this.setData({
        userData: await tool.login(),
        loginingWelcomText: (() => {
          const now = new Date();
          const hour = now.getHours();

          if (hour >= 0 && hour < 6) {
            return "凌晨好";
          } else if (hour >= 6 && hour < 9) {
            return "早上好";
          } else if (hour >= 9 && hour < 12) {
            return "上午好";
          } else if (hour === 12) {
            return "中午好";
          } else if (hour > 12 && hour < 18) {
            return "下午好";
          } else if (hour >= 18 && hour < 20) {
            return "傍晚好";
          } else {
            return "晚上好";
          }
        })()
      })
      // 获取主页数据
      await this.handleGetHomeData()
      // connect ws
      ws.init(tool.store.getItem('openId'))
      // 设置mainCurrentPageIndex
      tool.store.setItem('mainCurrentPageIndex', 0)
      tool.store.onChange('mainCurrentPageIndex', () => {
        this.setData({
          mainCurrentPageIndex: tool.store.getItem('mainCurrentPageIndex'),
          title: (() => {
            switch (tool.store.getItem('mainCurrentPageIndex')) {
              case 0:
                return '后勤管理服务中心'
              case 1:
                return '巡查'
              case 2:
                return this.getMessageTitle()
              case 4:
                return '我的'
              case 5:
                return '统计'
              case 6:
                return '后勤e码通'
            }
          })()
        })
      })
      this.setData({
        loading: false,
        showFeedBack: (() => {
          if (this.data.userData === undefined) {

            return true
          }
          return false
        })()
      })
      tool.store.setItem('requestShowLoading', true)

      // 设置 使用旧版界面
      tool.store.setItem('useOldUI', wx.getStorageSync('useOldUI'))

      // 自动更新未读通知数
      tool.store.onChange('updateNotifications', () => tool.updateUnreadNum())
      tool.store.setItem('updateNotifications')
      tool.store.onChange('unreadNum', () => {
        if (this.data.mainCurrentPageIndex == 2) this.setData({
          title: this.getMessageTitle()
        })
      })
      tool.updateUnreadNum()

      // 初始化聊天室
      tool.chatRoom.handleWS()

      // 检查更新
      tool.handleUpdateProgram()

      if (!wx.getStorageSync('subNotif')) {
        this.setData({
          showOpenSubNotif: true
        })
        await new Promise((resolve, reject) => {
          tool.store.onChange('subNotif', () => resolve())
        })
      }

      // 扫描二维码
      tool.handleOptions(options)
    }, (error) => {
      tool.handleShowModel(error, false)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})